package org.itboys.weixin.tools;

import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.itboys.weixin.entity.WeixinUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

/**
 * 关注微信账号时，同时注册成会员
 * 避免包之间的相互引用
 * @author weisky
 *
 * 2016年4月11日
 */
public class MemberActionThread {
	
	protected static Logger logger = LoggerFactory.getLogger(MemberActionThread.class);

	//创建一个定长线程池，池的大小根据CPU支持的进程数来分配
	private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); 
	
	/**
	 * 新增会员信息
	 * @param user
	 * @param url : 请求地址
	 * @param recId : 推荐人ID
	 */
	public static void addMember(WeixinUser user, String addUrl, Long recId){
		fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				try{
					Map<String, Object> memberparam = Maps.newHashMapWithExpectedSize(9);
					memberparam.put("username", URLEncoder.encode(user.getNickname(),"utf-8"));
					memberparam.put("nickname", URLEncoder.encode(user.getNickname(),"utf-8"));
					memberparam.put("logo", user.getHeadimgurl());
					memberparam.put("thirdType", "weixin");
					memberparam.put("thirdObjId", user.getId());//用户的微信账号信息跟会员的信息关联  以后推送信息、生成二维码等信息时要用
					memberparam.put("sex", user.getSex());
					memberparam.put("mobile", user.getMobile());
					memberparam.put("weixinId", user.getWeixinId());
					memberparam.put("openId", user.getOpenid());
					memberparam.put("recId", recId);
					HttpHelper.doGet(addUrl, memberparam);
				}catch(Exception e){
					e.printStackTrace();
					logger.error("MemberActionThread.addMember err", e);
				}
			}
		});
	}
	
}
